package com.example;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Date;

public class WeakReferenceTest {

    public static class Car {
        @Override
        public String toString(){
            return "这是一辆车";
        }
    }

    public static void main(String[] args) {
        ReferenceQueue<Car> referenceQueue = new ReferenceQueue<>();
        WeakReference<Car> weakReference = new WeakReference<>(new Car(), referenceQueue);

        System.out.println("referenceQueue.poll()：" + referenceQueue.poll());

        while (true){
            Date date = new Date();
            if(null != weakReference.get()){
                System.out.println(date + " - " + weakReference.get());
            }else {
                System.out.println(date + " - " +"car 已经被GC回收");
                if(referenceQueue.poll() == weakReference){
                    System.out.println("weakReference被放入到了referenceQueue");
                }
                break;
            }
        }
    }
}
